package com.example.takeaway.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.takeaway.common.CustomException;
import com.example.takeaway.entity.Category;
import com.example.takeaway.entity.Setmeal;
import com.example.takeaway.entity.SetmealDish;
import com.example.takeaway.entity.SetmealDto;
import com.example.takeaway.mapper.SetMealMapper;
import com.example.takeaway.service.CategoryService;
import com.example.takeaway.service.SetMealService;
import com.example.takeaway.service.SetmealDishService;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@AllArgsConstructor
@Service
public class SetMealServiceImpl extends ServiceImpl<SetMealMapper, Setmeal> implements SetMealService {


    private final SetmealDishService setmealDishService;

    /**
     * 新增菜品
     * @param setmealDto
     */

    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {

        //保存套餐的基本信息 操作setmeal 执行insert操作
        this.save(setmealDto);

        Long id = setmealDto.getId();

        //保存保存和菜品多的关联信息 操作setmeal_dish 执行的inset操作

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        setmealDishes = setmealDishes.stream().map((item) -> {

            item.setSetmealId(id);
            return item;

        }).collect(Collectors.toList());

        setmealDishService.saveBatch(setmealDishes);


    }

    /**
     * 删除套餐 同时需要删除套餐和菜品的关联数据
     * @param ids
     */

    @Transactional
    public void removeWithDish(List<Long> ids) {

        //查询套餐状态 确定是否可用删除
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Setmeal::getId,ids);
        wrapper.eq(Setmeal::getStatus , 1);  //1是禁用


        long count = this.count(wrapper);
        if(count > 0) {

            //如果不能删除 抛出一个异常
            throw new CustomException("套餐正在售卖中,不能删除");


        }


        //如果可以删除 先删除套餐表中的数据

        this.removeByIds(ids);


        //构造条件
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SetmealDish::getSetmealId,ids);

        //删除关系表中的数据
        setmealDishService.remove(queryWrapper);


    }



}
